//
//  PreviewResumeViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/9/17.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "PreviewResumeViewController.h"
#import "ResumeInfo.h"
#import "JobExpTableViewCell.h"
#import "EduExpTableViewCell.h"

@interface PreviewResumeViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *ResumeName;
@property (weak, nonatomic) IBOutlet UIImageView *headPic;
//基本信息
@property (weak, nonatomic) IBOutlet UIView *BasicInfoView;
@property (weak, nonatomic) IBOutlet UILabel *myName;
@property (weak, nonatomic) IBOutlet UILabel *sex;
@property (weak, nonatomic) IBOutlet UILabel *ancestralHome;
@property (weak, nonatomic) IBOutlet UILabel *birthday;
@property (weak, nonatomic) IBOutlet UILabel *address;
@property (weak, nonatomic) IBOutlet UILabel *phone;
@property (weak, nonatomic) IBOutlet UILabel *email;
@property (weak, nonatomic) IBOutlet UILabel *workDate;
@property (weak, nonatomic) IBOutlet UILabel *desc;

//求职意向
@property (weak, nonatomic) IBOutlet UIView *positionView;
@property (weak, nonatomic) IBOutlet UILabel *jobWantState;
@property (weak, nonatomic) IBOutlet UILabel *salaryWant;
@property (weak, nonatomic) IBOutlet UILabel *postionWant;

//工作经历
@property (weak, nonatomic) IBOutlet UIView *workExpView;
@property (weak, nonatomic) IBOutlet UITableView *workExpTableView;

//教育背景
@property (weak, nonatomic) IBOutlet UIView *educationView;
@property (weak, nonatomic) IBOutlet UITableView *eduTableView;

//个人优势
@property (weak, nonatomic) IBOutlet UIView *advantageView;
@property (weak, nonatomic) IBOutlet UILabel *advantage;

@property (weak, nonatomic) IBOutlet UIButton *inviteBtn;
@property (strong, nonatomic) ResumeInfo *resumeInfo;
@property (weak, nonatomic) IBOutlet UIButton *returnToLive;

@property (strong, nonatomic) UIButton *collectBtn;

//两个tableview的height
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *workExpHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eduHeight;

@end

@implementation PreviewResumeViewController

- (void)viewWillAppear:(BOOL)animated
{
	[self getResumeInfo];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view from its nib.
	
	self.navigationItem.title = @"简历详情";
	self.headPic.layer.cornerRadius = self.headPic.frame.size.height/2;
	self.headPic.clipsToBounds = YES;
	self.inviteBtn.layer.cornerRadius = 10;
	self.inviteBtn.clipsToBounds = YES;
	self.inviteBtn.backgroundColor = UIMainColorRGB;
	[self.inviteBtn addTarget:self action:@selector(inviteAction:) forControlEvents:UIControlEventTouchUpInside];
	if (self.shouldShowInviteBtn) {
		self.inviteBtn.hidden = NO;
		_collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_collectBtn setBackgroundImage:IMAGE(@"job_icon_uncollect") forState:UIControlStateNormal];
		[_collectBtn setBackgroundImage:IMAGE(@"job_icon_collected") forState:UIControlStateSelected];
		[_collectBtn addTarget:self action:@selector(collectOrCancelCollect) forControlEvents:UIControlEventTouchUpInside];
		UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_collectBtn];
		self.navigationItem.rightBarButtonItem = item;
	}
	else {
		self.inviteBtn.hidden = YES;
	}
	
	self.workExpTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.workExpTableView registerNib:[UINib nibWithNibName:@"JobExpTableViewCell" bundle:nil] forCellReuseIdentifier:@"jobCell"];
	self.workExpTableView.dataSource = self;
	self.workExpTableView.delegate = self;
	
	self.eduTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.eduTableView registerNib:[UINib nibWithNibName:@"EduExpTableViewCell" bundle:nil] forCellReuseIdentifier:@"eduCell"];
	self.eduTableView.dataSource = self;
	self.eduTableView.delegate = self;
	[self getResumeInfo];
	
	if (self.isFromLive) {
		[self.returnToLive addTarget:self action:@selector(returnTolive:) forControlEvents:UIControlEventTouchUpInside];
		self.returnToLive.hidden = NO;
	}
}

- (void)updateViewConstraints
{
	[super updateViewConstraints];
}
- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)assignToUI
{
	self.ResumeName.text = self.resumeInfo.title;
	[self.headPic sd_setImageWithURL:[NSURL URLWithString:self.resumeInfo.head_img]];
	self.myName.text = self.resumeInfo.name;
	if ([self.resumeInfo.sex isEqualToString:@"1"]) {
		self.sex.text = @"男";
	}
	else {
		self.sex.text = @"女";
	}
	
	self.ancestralHome.text = self.resumeInfo.ancestral_home;
	
	self.birthday.text = @"";
	if (self.resumeInfo.birth_date.length >= 8) {
		NSString *yearStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr = [self.resumeInfo.birth_date substringWithRange:NSMakeRange(6, 2)];
		self.birthday.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr, monthStr, dayStr];
	}
	
	self.address.text = [NSString stringWithFormat:@"%@ %@",self.resumeInfo.district, self.resumeInfo.address];
	self.phone.text = self.resumeInfo.mobile;
	self.email.text = self.resumeInfo.email;
	
	self.workDate.text = @"";
	if (self.resumeInfo.work_date.length >= 8) {
		NSString *yearStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr2 = [self.resumeInfo.work_date substringWithRange:NSMakeRange(6, 2)];
		self.workDate.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr2, monthStr2, dayStr2];
	}
	
	self.desc.text = self.resumeInfo.desc;
	NSInteger statusNum = [self.resumeInfo.apply_status integerValue];
	if (statusNum == 0) {
		self.jobWantState.text = @"已离职";
	}
	else if(statusNum == 1){
		self.jobWantState.text = @"在职";
	}
	self.postionWant.text = self.resumeInfo.category_title;
	self.salaryWant.text = self.resumeInfo.salary;
	self.advantage.text = self.resumeInfo.superiority;
	[self.advantage sizeToFit];
	
	NSLog(@"is selected?? %ld", self.resumeInfo.collection_status);
	if (self.resumeInfo.collection_status == 1) {
		[self.collectBtn setSelected:YES];
	}
	else {
		[self.collectBtn setSelected:NO];
	}
	
}

//TableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (tableView == self.workExpTableView) {
		JobExpTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"jobCell" forIndexPath:indexPath];
		cell.info = self.resumeInfo.work_list[indexPath.row];
		if (self.isFromLive) {
			cell.startDate.font = kUHSystemFontWithSize(10);
			cell.endDate.font = kUHSystemFontWithSize(10);
			[cell.startDate sizeToFit];
			[cell.endDate sizeToFit];
		}
		return cell;
	}
	else {
		EduExpTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eduCell" forIndexPath:indexPath];
		cell.info = self.resumeInfo.educational_list[indexPath.row];
		return cell;
	}
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if (tableView == self.workExpTableView) {
		return self.resumeInfo.work_list.count;
	}
	else {
		return self.resumeInfo.educational_list.count;
	}
	
}

//网上说不加这个的话会先执行heightForRow之后再执行cellForRowAtIndex而导致高度无法自适应，然而字数结果貌似不实现亦可。。
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (tableView == self.workExpTableView) {
		
		return 120;
	}
	else {
		return 120;
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (tableView == self.workExpTableView) {
		tableView.rowHeight = UITableViewAutomaticDimension;
		return tableView.rowHeight;
	}
	else {
		return 120;
	}
}
- (void)getResumeInfo
{
	//NSNumber *resumeIdNum = [NSNumber numberWithInteger:[self.resumeId integerValue]];
	NSDictionary *param = @{
							@"resume_id":self.resumeId
							};
	[[NetworkTool sharedTool] requestWithName:@"获取对应简历" URLString:APIGetResume parameters:param method:@"POST" callBack:^(id responseObject) {
		
		NSDictionary *dict = responseObject[@"data"];
		[self.resumeInfo setValuesForKeysWithDictionary:dict];
		[self assignToUI];
		[self.workExpTableView reloadData];
		self.workExpHeight.constant = self.workExpTableView.contentSize.height;
		[self.eduTableView reloadData];
		self.eduHeight.constant = self.eduTableView.contentSize.height;
		//[self updateViewConstraints];
	}];
}

- (void)inviteAction: (UIButton *)sender
{
	NSDictionary *param = @{@"resume_id" : self.resumeId};
	[[NetworkTool sharedTool] requestWithName:@"邀约面试" URLString:APIMakeInvitation parameters:param method:@"POST" callBack:^(id responseObject) {
		NSString *resultState = responseObject[@"data"][@"status"];
		if ([resultState integerValue] == 1) {
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"邀请成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:alert animated:YES completion:nil];
		}
		else
		{
			[self presentViewController:[LZCTools alertMessage:responseObject[@"data"][@"message"]] animated:YES completion:nil];
		}
		
	}];
}

- (void)returnTolive:(UIButton *)sender {
	NSLog(@"i was called");
	[self.parentViewController removeChild:self];
}

- (void)collectOrCancelCollect {
	
	NSDictionary *dict;
	NSString *url;
	
	if (self.collectBtn.isSelected) {
		url = APICancelCollectJobOrResume;
		dict = @{@"type":@"1",
				 @"resume_ids":self.resumeInfo.resumeId
				 };
	}
	else {
		url = APICollectJobOrResume;
		dict = @{@"type":@"1",
				 @"resume_id":self.resumeInfo.resumeId
				 };
	}	[[NetworkTool sharedTool] requestWithName:@"收藏岗位" URLString:url parameters:dict method:@"POST" callBack:^(id responseObject) {
		NSString *status = responseObject[@"data"][@"status"];
		if ([status integerValue] == 1) {
			[self.collectBtn setSelected:!self.collectBtn.isSelected];
            if (self.collectBtn.isSelected) {
                [LZCTools HUDMessage:@"收藏成功" delay:1.0];
            }
            else {
                [LZCTools HUDMessage:@"已取消收藏" delay:1.0];
            }
		}
	}];
}

- (ResumeInfo *)resumeInfo
{
	if (!_resumeInfo) {
		_resumeInfo = [[ResumeInfo alloc] init];
	}
	return _resumeInfo;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
